package com.example.modules.security.service;

import com.example.exception.BadRequestException;
import com.example.modules.security.security.vo.JwtUser;
import com.example.modules.system.entity.SysUser;
import com.example.modules.system.service.SysRoleService;
import com.example.modules.system.service.SysUserService;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


/**
 * @author Zheng Jie
 * @date 2018-11-22
 */
@Service("userDetailsService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final SysUserService sysUserService;

    private final SysRoleService sysRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) {
        SysUser sysUser = sysUserService.findByName(username);
        if (sysUser == null) {
            throw new BadRequestException("账号不存在");
        } else {
//            if (!user.getEnabled()) {
//                throw new BadRequestException("账号未激活");
//            }
            return createJwtUser(sysUser);
        }
    }

    private UserDetails createJwtUser(SysUser user) {
        return new JwtUser(
                user.getId(),
                user.getUsername(),
                user.getSex(),
                user.getPassword(),
                user.getEmail(),
                user.getMobile(),
                sysRoleService.mapToGrantedAuthorities(user),
                user.getCreateTime()
        );
    }
}
